package blog.controller;

import blog.entity.Article;
import blog.entity.CateGory;
import blog.entity.Tag;
import blog.entity.User;
import blog.service.ArticleService;
import blog.service.CateGoryService;
import blog.service.TagService;
import cn.hutool.Hutool;
import cn.hutool.http.HtmlUtil;
import com.github.pagehelper.PageInfo;
import org.aspectj.weaver.ast.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller @RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;
    @Resource
    private CateGoryService cateGoryService;
    @Resource
    private TagService tagService;

    @RequestMapping("")
    public String articleList(@RequestParam(required = false,defaultValue = "1") Integer pageIndex, @RequestParam(required = false,defaultValue = "10") Integer pageSize, Map map){
        /*查询分页数据*/
        PageInfo<Article> pageInfo = articleService.getPageArticleList(pageIndex,pageSize);
        map.put("pageInfo",pageInfo);
        map.put("pageUrlPrefix","article?pageIndex");
        return "article/article-list";
    }
    //删除文章
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    public void deleteArticle(@PathVariable("id") Integer id) {
         articleService.deleteArticleById(id);
    }

    /**
     * 转到文章发布页，并且带有全部分类,全部标签信息
     * @param map 用于传作用域数据
     * @return 文章发布页
     */
    @RequestMapping("/insert")
    public String forInsertArticle(Map map){
        //查询所有分类信息
        List<CateGory> cateGoryList = cateGoryService.getAllCateGory();
        //查询所有的标签信息
        List<Tag> tagList = tagService.findAllTag();
        map.put("cateGoryList",cateGoryList);
        map.put("tagList",tagList);
        return "article/article-insert";
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String addActicle(HttpServletRequest request){
        Article article = new Article();
        //文章标题
        String articleTitle = request.getParameter("articleTitle");
        article.setArticleTitle(articleTitle);
        //文章内容
        String articleContent = request.getParameter("articleContent");
        article.setArticleContent(articleContent);
        //创建文章的用户
        User user =(User) request.getSession().getAttribute("session_user");
        if(user!=null){
            article.setArticleUserId(user.getUserId());
        }
        //文章状态
        Integer articleStatus = Integer.parseInt(request.getParameter("articleStatus"));
        article.setArticleStatus(articleStatus);
        //把几个参数置成初始值 0
        article.setArticleViewCount(0);
        article.setArticleLikeCount(0);
        article.setArticleCommentCount(0);
        //文章创建事件
        article.setArticleCreateTime(new Date());
        //文章更新事件
        article.setArticleUpdateTime(new Date());
        //文章排序
        article.setArticleOrder(1);
        //文章是否回复
        article.setArticleIsComment(1);
        //文章摘要
        String articleSummary = HtmlUtil.cleanHtmlTag(articleContent);
        article.setArticleSummary(articleSummary.length()>150?articleSummary.substring(0,150):articleSummary);
        //获取一级分类
        int parentCateGoryId =Integer.parseInt(request.getParameter("articleParentCategoryId"));
        //获取二级分类
        int childCateGoryId =Integer.parseInt(request.getParameter("articleChildCategoryId"));
        //装入分类列表
        List<CateGory> cateGoryList = new ArrayList<>();
        cateGoryList.add(new CateGory(parentCateGoryId));
        cateGoryList.add(new CateGory(childCateGoryId));
        //获取前台穿过来的所有标签
        List<Tag> tagList = new ArrayList<>();
        String [] articleTagIds = request.getParameterValues("articleTagIds");
        for (String tagId:articleTagIds){
            tagList.add(new Tag(Integer.parseInt(tagId)));
        }
        //将分类和标签列表添加到文章中
        article.setTagList(tagList);
        article.setCategoryList(cateGoryList);
        //添加文章
        articleService.addArticle(article);
        return "forward:/article";
    }
    //添加草稿
    @RequestMapping("/insertDraftSubmit")
    public String  insertDraftSubmit(HttpServletRequest request){
         Article article = new Article();
         //文章标题
         String articleTitle = request.getParameter("articleTitle");
         //文章内容
         String articleContent = request.getParameter("articleContent");
         article.setArticleTitle(articleTitle);
         article.setArticleContent(articleContent);
         User user = (User) request.getSession().getAttribute("session_user");
         if(user!=null)
           article.setArticleUserId(user.getUserId());
         //给这些属性设置值
         article.setArticleViewCount(0);
         article.setArticleCommentCount(0);
         article.setArticleLikeCount(0);
         article.setArticleIsComment(0);
         article.setArticleStatus(Integer.parseInt(request.getParameter("articleStatus")));
         article.setArticleOrder(1);
         //文章更新和创建时间
         article.setArticleUpdateTime(new Date());
         article.setArticleCreateTime(new Date());
         //文章摘要
         String articleSummary = HtmlUtil.cleanHtmlTag(articleContent);
         article.setArticleSummary(articleSummary.length()>150?articleSummary.substring(0,150):articleSummary);
         articleService.addDraft(article);
         request.setAttribute("msg","保存成功");
         return "forward:/user/login";
    }
    //修改文章
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id,Map map){
        Article article = articleService.getArticleById(id);
        //在文章-分类关系表中查找出这篇文章一级分类
        Integer cateGoryPid = cateGoryService.getCateGoryPid(id);
        //在文章-分类关系表中查找出这篇文章二级分类
        Integer cateGoryChildrenId = cateGoryService.getCateGoryChildrenId(id);
        //查询所有的分类信息
        List<CateGory> cateGoryList = cateGoryService.findAll();
        //查询所有的标签信息
        List<Tag> tagList = tagService.findAllTag();
        //查询这篇文章的标签信息
        List<Tag> articleTagList = tagService.getArticleTag(id);
        map.put("articleTagList",articleTagList);
        map.put("cateGoryList",cateGoryList);
        map.put("tagList",tagList);
        map.put("cateGoryPid",cateGoryPid);
        map.put("cateGoryChildrenId",cateGoryChildrenId);
        map.put("article",article);
        return "article/article-edit";
    }
    @RequestMapping("/uploadImg")
    public String uploadImg(MultipartHttpServletRequest request) throws IOException {
        //imgFile 这个名称是固定的
        MultipartFile file =request.getFile("imgFile");
        //生成一个随机的文件名
        String newName=UUID.randomUUID().toString()+".jpg";
        File destFile=new File("D:/imguploads/"+newName);
        String path="http://localhost:8080/uploads/"+ newName;
        file.transferTo(destFile);
        return "{\"error\":0,\"url\":\""+path+"\"}" ;
    }
}
